<template>
  <div class="admin-container auto-height-container">
    <vab-query-form>
      <vab-query-form-left-panel :span="8">
        <el-button v-permissions="{
          permission: ['system:admin:doAdd']
        }" type="primary" @click="handleAdd" :icon="Plus">新增</el-button>
      </vab-query-form-left-panel>
      <vab-query-form-right-panel :span="16">
        <el-form :inline="true" :model="queryForm">
          <el-form-item style="margin-right: 10px !important;">
            <el-input v-model="queryForm.nickname" placeholder="请输入管理员昵称" clearable @keyup.enter="fetchData" />
          </el-form-item>
          <el-form-item style="margin-right: 10px !important;">
            <el-select v-model="queryForm.status" placeholder="请选择状态" clearable filterable>
              <el-option label="正常" :value="1" />
              <el-option label="禁用" :value="0" />
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="fetchData">查询</el-button>
            <el-button @click="resetQuery">重置</el-button>
          </el-form-item>
        </el-form>
      </vab-query-form-right-panel>
    </vab-query-form>

    <el-table v-loading="loading" :data="list" border height="100%">
      <el-table-column label="头像" width="80" align="center" header-align="center">
        <template #default="{ row }">
          <el-avatar :size="32" :src="row.avatar">{{ row.nickname?.substring(0, 1) }}</el-avatar>
        </template>
      </el-table-column>
      <el-table-column prop="admin_id" label="ID" width="80" align="center" show-overflow-tooltip />
      <el-table-column prop="username" label="用户名" min-width="120" align="center" show-overflow-tooltip />
      <el-table-column prop="nickname" label="昵称" min-width="120" align="center" show-overflow-tooltip />
      <el-table-column label="角色" min-width="160" align="center">
        <template #default="{ row }">
          <el-space wrap>
            <el-tag 
              v-for="roleItem in row.roles" 
              :key="roleItem.id"
              :type="roleItem.role.code === 'super_admin' ? undefined : 'info'"
              size="small"
            >
              {{ roleItem.role.name }}
            </el-tag>
          </el-space>
        </template>
      </el-table-column>
      <el-table-column prop="status" label="状态" width="80" align="center">
        <template #default="{ row }">
          <el-tag :type="row.status === 1 ? 'success' : 'danger'">
            {{ row.status === 1 ? '正常' : '禁用' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="last_login_ip" label="最后登录IP" min-width="120" align="center" show-overflow-tooltip />
      <el-table-column prop="last_login_time" label="最后登录时间" min-width="160" align="center" show-overflow-tooltip />
      <el-table-column prop="create_time" label="创建时间" min-width="160" align="center" show-overflow-tooltip />
      <el-table-column label="操作" width="200" align="center" fixed="right">
        <template #default="{ row }">
          <el-button 
            v-permissions="{
              permission: ['system:admin:doEdit']
            }" 
            type="primary" 
            link 
            @click="handleEdit(row)"
            :disabled="row.username === 'admin'"
          >编辑</el-button>
          <el-button 
            v-permissions="{
              permission: ['system:admin:doDelete']
            }" 
            type="danger" 
            link 
            @click="handleDelete(row)"
            :disabled="row.username === 'admin'"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <vab-pagination v-model:current-page="queryForm.pageNo" v-model:page-size="queryForm.pageSize" :total="total"
      @current-change="fetchData" @size-change="fetchData" />

    <admin-form-edit v-model:visible="dialogVisible" :type="dialogType" :current-row="currentRow"
      @success="fetchData" />
  </div>
</template>

<script setup lang="ts">
import { ref, reactive } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus } from '@element-plus/icons-vue'
import { getAdminList, deleteAdmin } from '/@/api/admin'
import type { AdminForm } from '/@/api/admin'
import AdminFormEdit from './components/AdminForm.vue'

const loading = ref(false)
const list = ref([])
const total = ref(0)
const dialogVisible = ref(false)
const dialogType = ref<'add' | 'edit'>('add')
const currentRow = ref<AdminForm | null>(null)

const queryForm = reactive({
  pageNo: 1,
  pageSize: 10,
  nickname: '',
  status: '',
})

// 获取管理员列表
const fetchData = async () => {
  try {
    loading.value = true
    const { data } = await getAdminList(queryForm)
    list.value = data.list
    total.value = data.total
  } catch (error) {
    console.error('获取管理员列表失败:', error)
  } finally {
    loading.value = false
  }
}

// 重置查询
const resetQuery = () => {
  queryForm.nickname = ''
  queryForm.status = ''
  fetchData()
}

// 处理新增
const handleAdd = () => {
  dialogType.value = 'add'
  currentRow.value = null
  dialogVisible.value = true
}

// 处理编辑
const handleEdit = (row: AdminForm) => {
  if (row.username === 'admin') {
    ElMessage.warning('超级管理员不能修改')
    return
  }
  dialogType.value = 'edit'
  currentRow.value = row
  dialogVisible.value = true
}

// 处理删除
const handleDelete = async (row: AdminForm) => {
  if (row.username === 'admin') {
    ElMessage.warning('超级管理员不能删除')
    return
  }

  try {
    await ElMessageBox.confirm(
      '确定要删除该管理员吗？删除后将无法恢复！',
      '删除确认',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }
    )

    await deleteAdmin(row.admin_id!)
    ElMessage.success('删除成功')
    fetchData()
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除失败:', error)
    }
  }
}

onMounted(() => {
  fetchData()
})
</script>

<style lang="scss" scoped>
:deep(.el-button.is-disabled) {
  opacity: 0.6;
  cursor: not-allowed;
}

:deep(.el-space) {
  justify-content: center;
}
</style>